package com.nacol.demo.contract.controller;

import cn.hutool.core.lang.Assert;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.nacol.demo.contract.entity.InstanceFlag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Nacol(姚秋实)
 * @Date 2023/12/11
 * @Title 实例打标控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/instance-flag")
public class InstanceFlagController {

    private final NacosDiscoveryProperties discoveryProperties;

    /**
     * @Author Nacol(姚秋实)
     * @Date 2023/12/11
     * @Title 修改 MetaData（打标更新）
     * @Description 此方法仅作为演示：修改被调用Instance的MetaData（可根据实际需要修改具体逻辑）
     * ApiPost传送门：https://console-docs.apipost.cn/preview/03c77141b7da90a7/4538142d98eb81f0
     */
    @PutMapping("/modify")
    @SneakyThrows
    public void updateMetadata(@RequestBody InstanceFlag instanceFlag) {
        // STEP 获取当前 NameSpace
        NamingService namingService = discoveryProperties.namingServiceInstance();

        // STEP 获取 NameSpace 下的指定服务实例集合
        List<Instance> instances = namingService.getAllInstances(instanceFlag.getServiceName());

        // STEP 获取当前节点
        Instance currentInstance = instances.stream()
                /**
                 * STEP 过滤：获取当前节点，即：IP和端口相等
                 * 可根据实际需求更改逻辑
                 */
                .filter(instance -> instance.getIp().equals(discoveryProperties.getIp())
                        && instance.getPort() == discoveryProperties.getPort())
                .findFirst()
                .get();
        Assert.notNull(currentInstance, () -> new RuntimeException("Not current instance found"));

        // STEP 更新 MetaData
        // 获取当前节点当前 MetaData
        Map<String, String> metaData = new HashMap<>(currentInstance.getMetadata());
        // 参数 MetaData 将当前 MetaData 更新
        metaData.putAll(instanceFlag.getMetaData());
        currentInstance.setMetadata(metaData);

        // STEP 更新 Nacos
        namingService.registerInstance(instanceFlag.getServiceName(), currentInstance);
    }

}
